﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Net;

namespace SysSU.Net
{
    public class TCPNetwokServer : INetworkServer
    {
        private TcpListener tcpListener;
        private Thread listenThread;

        public bool Stopped { get; private set; }
        public INetworkObserver Observer { get; set; }

        public TCPNetwokServer(int port)
        {
            tcpListener = new TcpListener(IPAddress.Any, port);                        
        }

        public void Start()
        {
            if (Observer == null)
            {
                throw new InvalidOperationException("No network observer was defined");
            }

            try
            {
                tcpListener.Start();
                while (!Stopped)
                {
                    var client = tcpListener.AcceptTcpClient();
                    new Thread(new ClientWorker(Observer, client.Client).Work).Start();
                }
            }
            catch (Exception ex)
            {
                if (!Stopped)
                {
                    throw new IOException("Error accepting client connection", ex);
                }
            }
        }

        public void Stop()
        {
            Stopped = true;
            tcpListener.Stop();
        }
    }
}
